package com.arpa.ntocc.common.service.impl;

import cn.hutool.core.util.IdUtil;
import com.arpa.ntocc.common.common.cache.RoleCache;
import com.arpa.ntocc.common.common.cache.RoleCacheDO;
import com.arpa.ntocc.common.common.util.UserUtil;
import com.arpa.ntocc.common.domain.entity.PartyRole;
import com.arpa.ntocc.common.mapper.PartyRoleMapper;
import com.arpa.ntocc.common.service.IPartyRoleService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 登录账号角色 服务实现类
 * </p>
 *
 * @author LEO
 * @since 2019-08-09
 */
@Service
public class PartyRoleServiceImpl extends ServiceImpl<PartyRoleMapper, PartyRole> implements IPartyRoleService {

    @Autowired
    RoleCache roleCache;

    /**
     * 保存登录账号角色信息
     *
     * @param partyCode
     * @param roleCodes
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean save(String partyCode, List<String> roleCodes) {
        //删除老的用户角色关系
        baseMapper.delete(new QueryWrapper<PartyRole>().lambda().eq(PartyRole::getPartyCode, partyCode));
        List<PartyRole> partyRoles = roleCodes.stream().map(roleCode -> {
            PartyRole partyRole = new PartyRole();
            partyRole.setCode(IdUtil.simpleUUID());
            partyRole.setPartyCode(partyCode);
            partyRole.setRoleCode(roleCode);
            partyRole.setCreatedBy(UserUtil.getCode());
            return partyRole;
        }).collect(Collectors.toList());
        return this.saveBatch(partyRoles);
    }

    /**
     * 查询登录账号拥有角色信息
     *
     * @param partyCode
     * @return
     */
    @Override
    public List<RoleCacheDO> listRoles(String partyCode) {
        //查询用户角色表
        List<RoleCacheDO> roleList = baseMapper.selectList(new QueryWrapper<PartyRole>().lambda().eq(PartyRole::getPartyCode, partyCode)).stream().map(partyRole -> {
            RoleCacheDO role = roleCache.get(partyRole.getRoleCode());
            return role;
        }).collect(Collectors.toList());
        return roleList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeByUserLoginId(String userLoginId) {
        baseMapper.removeByUserLoginId(userLoginId);
    }
}
